package com.lzx.reggie.controller

import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.lzx.reggie.common.R
import com.lzx.reggie.dto.DishDto
import com.lzx.reggie.entity.Dish
import com.lzx.reggie.entity.DishFlavor
import com.lzx.reggie.service.CategoryService
import com.lzx.reggie.service.DishFlavorService
import com.lzx.reggie.service.DishService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*


@RestController
@RequestMapping("/dish")

class DishController {

    companion object {
        val log: Logger = LoggerFactory.getLogger(AddressBookController::class.java)
    }

    @Autowired
    private lateinit var dishService: DishService

    @Autowired
    private lateinit var dishFlavorService: DishFlavorService

    @Autowired
    private lateinit var categoryService: CategoryService

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    fun save(@RequestBody dishDto: DishDto): R<String> {
        log.info(dishDto.toString())
        dishService.saveWithFlavor(dishDto)
        return R.success("新增菜品成功")
    }

    /**
     * 菜品信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    fun page(page: Long, pageSize: Long, name: String?): R<Page<*>> {

        //构造分页构造器对象
        val pageInfo = Page<Dish>(page, pageSize)
        val dishDtoPage = Page<DishDto>()

        //执行分页查询
        dishService.page(pageInfo,
            // 条件构造器
            KtQueryWrapper(Dish::class.java).apply {
                // 添加过滤条件
                like(name != null, Dish::name, name)
                // 添加排序条件
                orderByDesc(Dish::updateTime)
            })

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records")
        val records = pageInfo.records
        val list = records.map { item ->
            val dishDto = DishDto()
            BeanUtils.copyProperties(item, dishDto)
            val categoryId = item.categoryId //分类id
            //根据id查询分类对象
            val category = categoryService.getById(categoryId)

            dishDto.categoryName = category?.name

            dishDto
        }
        dishDtoPage.records = list
        return R.success(dishDtoPage)
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    operator fun get(@PathVariable id: Long): R<DishDto> {
        val dishDto = dishService.getByIdWithFlavor(id)
        return R.success(dishDto)
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    fun update(@RequestBody dishDto: DishDto): R<String> {
        log.info(dishDto.toString())
        dishService.updateWithFlavor(dishDto)
        return R.success("修改菜品成功")
    }

    @GetMapping("/list")
    fun list(dish: Dish): R<List<DishDto>> {

        val dishDtoList = dishService.list(
            //构造查询条件
            KtQueryWrapper(Dish::class.java).apply {
                eq(dish.categoryId != null, Dish::categoryId, dish.categoryId)
                // 添加条件，查询状态为1（起售状态）的菜品
                eq(Dish::status, 1)
                // 添加排序条件
                orderByAsc(Dish::sort)
                orderByDesc(Dish::updateTime)
            }).map { item: Dish ->
            val dishDto = DishDto()
            BeanUtils.copyProperties(item, dishDto)

            //根据id查询分类对象
            dishDto.categoryName = categoryService.getById(item.categoryId)?.name

            dishDto.flavors = dishFlavorService.list(
                // SQL:select * from dish_flavor where dish_id = ?
                KtQueryWrapper(DishFlavor::class.java).apply {
                    //当前菜品的id
                    eq(DishFlavor::dishId, item.id)
                })

            dishDto
        }

        return R.success(dishDtoList)
    }
}
